<template>
  <a-modal
    title="新增二手车车源"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-divider orientation="left">基本信息</a-divider>
      <a-form :form="form">
        <a-row>
          <a-col :md="12" :sm="24" >
            <a-form-item
              label="车源编号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入车源编号" v-decorator="['sourceNum', {rules: [{required: true, message: '请输入车源编号！'}]}]" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" >
            <a-form-item
              label="表显里程"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入表显里程（万公里）" v-decorator="['outsideMile', {rules: [{required: true, message: '请输入表显里程（万公里）！'}]}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24" >
            <a-form-item
              label="指导价"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入设置指导价" v-decorator="['guidePrice', {rules: [{required: true, message: '请输入指导价！'}]}]" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" >
            <a-form-item
              label="销售价格"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入销售价格" v-decorator="['salePrice', {rules: [{required: true, message: '请输入销售价格！'}]}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="上牌时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-date-picker
                format="YYYY-MM-DD"
                v-decorator="['registrationTime',{rules: [{ required: true, message: '上牌时间!' }]}]"
                placeholder="请选择时间"
                @change="onChangeRegistrationTime" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="年检时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-date-picker
                format="YYYY-MM-DD"
                v-decorator="['inspectAnnuallyTime',{rules: [{ required: true, message: '请输入时间!' }]}]"
                placeholder="请选择时间"
                @change="onChangeInspectAnnuallyTime" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="过户次数"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input-number style="width: 100%" placeholder="请输入过户次数" v-decorator="['transferNum', {rules: [{required: true, message: '请输入过户次数！'}]}]" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="钥匙数量"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input-number style="width: 100%" placeholder="请输入钥匙数量" v-decorator="['keyNum', {rules: [{required: true, message: '请输入钥匙数量！'}]}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="定金数量"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input-number style="width: 100%" placeholder="请输入定金金币数量" v-decorator="['depositPrice', {rules: [{required: true, message: '请输入定金金币数量！'}]}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="车牌所在地"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-select style="width: 100%" showSearch :filterOption="filterOption" placeholder="请设置省份" v-decorator="['licenseProvince', {rules: [{ required: true, message: '请设置区域！' }]}]" >
                <a-select-option v-for="(item,index) in proviceListData" :key="index" :value="item.name" @click="proviceSele(item)">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="城市"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-select style="width: 100%" placeholder="请设置城市" v-decorator="['licenseCity', {rules: [{ required: true, message: '请设置区域！' }]}]" >
                <a-select-option v-for="(item1, index1) in cityListData" :value="item1.name" :key="index1">
                  {{ item1.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="品牌"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-select :filterOption="filterOption" style="width: 100%" placeholder="请选择品牌" v-decorator="['brandId', {rules: [{ required: true, message: '请选择品牌！' }]}]" >
                <a-select-option v-for="(item,index) in brandListData" :key="index" :value="item.brandId" @click="brandNameSele(item)">{{ item.brandName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="车系"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-select howSearch :filterOption="filterOption" style="width: 100%" placeholder="请选择车系" v-decorator="['seriesId', {rules: [{ required: true, message: '请选择车系！' }]}]" >
                <a-select-opt-group v-for="(item,index) in subBrandListData" :key="index" :value="item.subBrandName" >
                  <span slot="label">{{ item.subBrandName }}</span>
                  <a-select-option v-for="(item1,index1) in item.carSeriesList" :key="index1" :value="item1.seriesId" @click="seriesNameSele(item1)">{{ item1.seriesName }}</a-select-option>
                </a-select-opt-group>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="车型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-select showSearch :filterOption="filterOption" style="width: 100%" placeholder="请选择车型" v-decorator="['modelId', {rules: [{ required: true, message: '请选择车型！' }]}]" >
                <a-select-option v-for="(item,index) in modelListData" :key="index" :value="item.id" >{{ item.modelName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="外观"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入外观" v-decorator="['outColor', {rules: [{required: true, message: '请输入外观！'}]}]" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="内饰"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入内饰" v-decorator="['inColor', {rules: [{required: true, message: '请输入内饰！'}]}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="亮点配置"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入亮点配置" v-decorator="['highlightsConfiguration', {rules: [{required: true, message: '请输入亮点配置！'}]}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">图片信息</a-divider>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="头部图片"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-upload
                name="head"
                :multiple="false"
                list-type="picture-card"
                :file-list="headList"
                @preview="handlePreview"
                :remove="handleChange"
                :customRequest="uploadFlowPic"
              >
                <div v-if="headList.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="前排座椅"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-upload
                name="frontSeat"
                :multiple="false"
                list-type="picture-card"
                :file-list="frontSeatList"
                @preview="handlePreview"
                :remove="handleChange"
                :customRequest="uploadFlowPic"
              >
                <div v-if="frontSeatList.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="其他图"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-upload
                name="other"
                :multiple="false"
                list-type="picture-card"
                :file-list="otherList"
                @preview="handlePreview"
                :remove="handleChange"
                :customRequest="uploadFlowPic"
              >
                <div v-if="otherList.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="总控台"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-upload
                name="masterControlPane"
                :multiple="false"
                list-type="picture-card"
                :file-list="masterControlPaneList"
                @preview="handlePreview"
                :remove="handleChange"
                :customRequest="uploadFlowPic"
              >
                <div v-if="masterControlPaneList.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="仪表盘"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-upload
                name="dashBoard"
                :multiple="false"
                list-type="picture-card"
                :file-list="dashBoardList"
                @preview="handlePreview"
                :remove="handleChange"
                :customRequest="uploadFlowPic"
              >
                <div v-if="dashBoardList.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="天窗"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-upload
                name="skyLight"
                :multiple="false"
                list-type="picture-card"
                :file-list="skyLightList"
                @preview="handlePreview"
                :remove="handleChange"
                :customRequest="uploadFlowPic"
              >
                <div v-if="skyLightList.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="左前45"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-upload
                name="frontRight45"
                :multiple="false"
                list-type="picture-card"
                :file-list="frontRight45List"
                @preview="handlePreview"
                :remove="handleChange"
                :customRequest="uploadFlowPic"
              >
                <div v-if="frontRight45List.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="右后45"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-upload
                name="backRight45"
                :multiple="false"
                list-type="picture-card"
                :file-list="backRight45List"
                @preview="handlePreview"
                :remove="handleChange"
                :customRequest="uploadFlowPic"
              >
                <div v-if="backRight45List.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="铭牌"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-upload
                name="nameplate"
                :multiple="false"
                list-type="picture-card"
                :file-list="nameplateList"
                @preview="handlePreview"
                :remove="handleChange"
                :customRequest="uploadFlowPic"
              >
                <div v-if="nameplateList.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <div class="clearfix">
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancelPreview">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { carSourceOldAdd, uploadFile, carSourceOldDetail } from '@/api/modular/main/carsourceold/carSourceOldManage'
  import { brandList, subBrandList, modelList } from '@/api/modular/main/carsource/carSource'
  import { proviceList } from '@/api/modular/main/area/area'
  import moment from 'moment'
  import 'moment/locale/zh-cn'
  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = error => reject(error)
    })
  }
  export default {
    data () {
      return {
        inspectAnnuallyTime: '',
        registrationTime: '',
        brandListData: [],
        subBrandListData: [],
        modelListData: [],
        proviceListData: [],
        cityListData: [],
        parameter: {},
        parameterCity: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        previewVisible: false,
        previewImage: '',
        fileList: [],
        headList: [],
        frontSeatList: [],
        otherList: [],
        masterControlPaneList: [],
        dashBoardList: [],
        skyLightList: [],
        frontRight45List: [],
        backRight45List: [],
        nameplateList: []
      }
    },
    methods: {
      // 初始化方法
      edit (res) {
        this.visible = true
        this.brandList() // 获取品牌列表
        this.proviceList() // 获取省份信息
        const param = { 'id': res.id }
        carSourceOldDetail(param).then(record => {
          setTimeout(() => {
            debugger
          this.form.setFieldsValue(
            {
              id: record.id,
              sourceNum: record.sourceNum,
              guidePrice: record.guidePrice,
              salePrice: record.salePrice,
              registrationTime: record.registrationTime,
              outsideMile: record.outsideMile,
              licenseProvince: record.licenseProvince,
              licenseCity: record.licenseCity,
              transferNum: record.transferNum,
              outColor: record.outColor,
              inColor: record.inColor,
              highlightsConfiguration: record.highlightsConfiguration,
              keyNum: record.keyNum,
              inspectAnnuallyTime: record.inspectAnnuallyTime,
              depositPrice: record.depositPrice,
              status: record.status,
              deleteFlag: record.deleteFlag,
              createBy: record.createBy,
              updateBy: record.updateBy,
              remark: record.remark,
              brandId: record.brandId,
              brandName: record.brandName,
              seriesId: record.seriesId,
              seriesName: record.seriesName,
              modelId: record.modelId,
              modelName: record.modelName
            }
          )
        }, 100)
        })
      },
      moment,
      onChangeInspectAnnuallyTime (value, dateString) {
        this.inspectAnnuallyTime = dateString
      },
      onChangeRegistrationTime (value, dateString) {
        this.registrationTime = dateString
      },
      /**
       * 关闭预览
       */
      handleCancelPreview() {
        this.previewVisible = false
      },
      /**
       * 图片预览
       */
      async handlePreview(file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      // 上传办理流程图文件方法
      uploadFlowPic (file) {
        const formData = new window.FormData()
        formData.append('file', file.file)
        if (file.filename === 'head') {
          formData.append('fileType', 101)
        }
        if (file.filename === 'frontSeat') {
          formData.append('fileType', 102)
        }
        if (file.filename === 'other') {
          formData.append('fileType', 103)
        }
        if (file.filename === 'masterControlPane') {
          formData.append('fileType', 104)
        }
        if (file.filename === 'dashBoard') {
          formData.append('fileType', 105)
        }
        if (file.filename === 'skyLight') {
          formData.append('fileType', 108)
        }
        if (file.filename === 'frontRight45') {
          formData.append('fileType', 109)
        }
        if (file.filename === 'backRight45') {
          formData.append('fileType', 110)
        }
        if (file.filename === 'nameplate') {
          formData.append('fileType', 111)
        }
        uploadFile(formData).then(res => {
          if (res.success) {
            // 调用组件内方法, 设置为成功状态
            file.onSuccess(res, file.file)
            file.status = 'done'
            if (file.filename === 'head') {
              this.headList.push({
                uid: res.data.fileUrl,
                name: file.file.name,
                status: 'done',
                url: res.data.fileUrl
              })
            }
            if (file.filename === 'frontSeat') {
              this.frontSeatList.push({
                uid: res.data.fileUrl,
                name: file.file.name,
                status: 'done',
                url: res.data.fileUrl
              })
            }
            if (file.filename === 'other') {
              this.otherList.push({
                uid: res.data.fileUrl,
                name: file.file.name,
                status: 'done',
                url: res.data.fileUrl
              })
            }
            if (file.filename === 'masterControlPane') {
              this.masterControlPaneList.push({
                uid: res.data.fileUrl,
                name: file.file.name,
                status: 'done',
                url: res.data.fileUrl
              })
            }
            if (file.filename === 'dashBoard') {
              this.dashBoardList.push({
                uid: res.data.fileUrl,
                name: file.file.name,
                status: 'done',
                url: res.data.fileUrl
              })
            }
            if (file.filename === 'skyLight') {
              this.skyLightList.push({
                uid: res.data.fileUrl,
                name: file.file.name,
                status: 'done',
                url: res.data.fileUrl
              })
            }
            if (file.filename === 'frontRight45') {
              this.frontRight45List.push({
                uid: res.data.fileUrl,
                name: file.file.name,
                status: 'done',
                url: res.data.fileUrl
              })
            }
            if (file.filename === 'backRight45') {
              this.backRight45List.push({
                uid: res.data.fileUrl,
                name: file.file.name,
                status: 'done',
                url: res.data.fileUrl
              })
            }
            if (file.filename === 'nameplate') {
              this.nameplateList.push({
                uid: res.data.fileUrl,
                name: file.file.name,
                status: 'done',
                url: res.data.fileUrl
              })
            }
          } else {
            file.onError()
            file.status = 'error'
          }
        })
      },
      /**
       * 删除图片调用
       */
      handleChange(file) {
        debugger
        // this.fileList = fileList
      },
      // 初始化方法
      add (record) {
        this.visible = true
        this.brandList() // 获取品牌列表
        this.proviceList() // 获取省份信息
        // 此处默认加载数据
      },
      /**
       * 获取区域
       */
      proviceList () {
        this.parameter.grade = 1
        proviceList(this.parameter).then((res) => {
          this.proviceListData = res.data
        })
      },
      /**
       * 选择省份获取城市
       */
      proviceSele (item) {
        debugger
        this.parameterCity.parentCode = item.code
        proviceList(this.parameterCity).then((res) => {
          debugger
          this.cityListData = res.data
        })
      },
      /**
       * 获取品牌
       */
      brandList () {
        brandList().then((res) => {
          this.brandListData = res.data
        })
      },
      /**
       * 品牌搜索
       */
      filterOption (value, option) {
        return option.componentOptions.children[0].text.indexOf(value) >= 0
      },
      /**
       * 选择数据库列表
       */
      brandNameSele (item) {
        subBrandList(item).then((res) => {
          this.subBrandListData = res.data
        })
      },
      /**
       * 选择数据库列表
       */
      seriesNameSele (item) {
        modelList(item).then((res) => {
          this.modelListData = res.data
        })
      },
      /**
       * 选择车型
       */
      modelNameSele (item) {
        modelList(item).then((res) => {
          this.modelListData = res.data
        })
      },
      /**
       * 提交表单
       */
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            for (const key in values) {
              if (typeof (values[key]) === 'object' && values[key] != null) {
                values[key] = JSON.stringify(values[key])
              }
            }
            /* 日期设置 */
            values['inspectAnnuallyTime'] = this.inspectAnnuallyTime
            values['registrationTime'] = this.registrationTime
            /* 图片设置 */
            values['headList'] = this.headList
            values['frontSeatList'] = this.frontSeatList
            values['otherList'] = this.otherList
            values['masterControlPaneList'] = this.masterControlPaneList
            values['dashBoardList'] = this.dashBoardList
            values['skyLightList'] = this.skyLightList
            values['frontRight45List'] = this.frontRight45List
            values['backRight45List'] = this.backRight45List
            values['nameplateList'] = this.nameplateList
            carSourceOldAdd(values).then((res) => {
              if (res.success) {
                this.$message.success('新增成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error('新增失败')// + res.message
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.visible = false
      }
    }
  }
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
